<template>
    <el-dialog v-model="preOrderVisible" title="订单预览" @close="closePreOrderDialog(false)">
        <el-table :data="tableData" height="300">
            <el-table-column property="name" label="商品名称" width="350"></el-table-column>
            <el-table-column property="price" label="价格" width="80"></el-table-column>
            <el-table-column property="num" width="50" label="数量"></el-table-column>
            <el-table-column property="total" label="总价" width="80"></el-table-column>
        </el-table>

        <el-form :model="form">
            <el-form-item label="收货地址">
                <el-select v-model="form.region" placeholder="选择地址">
                    <el-option
                        v-for="tab in tabledata1"
                        :key="tab.length"
                        :label="tab.name + '  ' + tab.phone + '  ' + tab.detail"
                        :value="tab.id"
                    ></el-option>
                </el-select>
            </el-form-item>
        </el-form>

        <el-button style="margin:0 100px 0px 50px;" @click="address = true" type="primary">管理地址</el-button>
        <!-- 地址管理 -->
        <el-dialog v-model="address" title="地址管理">
            <!-- 查看地址 -->
            <el-table :data="tabledata1" height="300">
                <el-table-column property="name" label="name" width="150"></el-table-column>
                <el-table-column property="phone" label="电话" width="120"></el-table-column>

                <el-table-column property="detail" label="地址" width="200"></el-table-column>
                <el-table-column prop label="操作" width="100">
                    <template #default="scope">
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete2(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 添加地址 -->
            <el-form
                label-width="80px"
                ref="addressfrom"
                :model="addressfrom"
                label-position="left"
                status-icon
                :rules="rules"
                style="clear: both;width:400px;margin-left:50px"
            >
                <el-form-item label="名字" prop="name">
                    <el-input v-model="addressfrom.name" type></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="addressfrom.phone" type></el-input>
                </el-form-item>
                <el-form-item label="地址" prop="detail">
                    <el-input v-model="addressfrom.detail" type></el-input>
                </el-form-item>
                <el-button type="primary" @click="addaddress('addressfrom')">添加</el-button>
            </el-form>
        </el-dialog>

        <template #footer>
            <span class="dialog-footer" style="margin-top:50px">
                <el-button
                    @click="() => {
                        closePreOrderDialog(false);
                    }"
                >取消</el-button>
                <el-button type="primary" @click="pAddOrder">下单</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { reactive, toRefs, ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessageBox, ElNotification } from "element-plus";

function loadData(state) {
    const params = {
        id: state.goodsId,
        // id: '39',
    };
    axios({
        url: "/getGoodsById",
        method: "get",
        params: params,
    }).then((res) => {
        // if (res.data.code == 200) {
        console.log(res.data);
        // state.tabledata2 = res.data.data;
        state.goodsDetail = res.data.data;
        state.total = state.goodsNum * res.data.data.price;


        state.tableData[0].name = res.data.data.name;
        state.tableData[0].price = res.data.data.price;
        state.tableData[0].num = state.goodsNum;
        state.tableData[0].total = state.total;

        // 获取地址
        axios({
            url: "/getAddressView",
            method: "get",
            params: {
                username: state.username
            },
        })
            .then((res1) => {
                if (res1.data.code == 200) {
                    var u = res1.data.data;
                    var i = 0;
                    state.tabledata1 = []
                    for (i; i < u.length; i++) {
                        state.tabledata1.push(u[i]);
                    }
                }
            })
            .catch((err) => {
                console.error();
            });

    });
}

//直接购买
function usePAddOrder(state, emit) {
    const pAddOrder = () => {
        if (state.form.region == '') {
            ElNotification({
                title: "提示",
                message: "请选择地址",
                type: "error",
                duration: 2000,
            });
        } else {
            const params = {
                t: '1',
                aid: state.form.region,
                username: state.username,
                num: state.goodsNum,
                money: state.total,
                gid: state.goodsId,
            };
            axios({
                url: "/addOrder",
                method: "get",
                params: params,
            }).then((res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    ElNotification({
                        title: "成功",
                        message: "购买成功",
                        type: "success",
                        duration: 2000,
                    });
                    emit('onClosePreOrderDialog', false, res.data.data);
                    window.location.href="/order"
                }
            });
        }

    }
    return {
        pAddOrder
    }
}

//删除地址
function handleDelete2(state) {
    const handleDelete2 = (index, row) => {
        axios({
            url: "/userAddressDel",
            method: "get",
            params: {
                id: row.id,
            },
        }).then((res) => {
            // console.log(res.data);
            if (res.data.code == 200) {
                ElNotification({
                    title: "成功",
                    message: "删除成功",
                    type: "success",
                    duration: 2000,
                });
                // getorder(state)
                loadData(state)
            } else {
                ElNotification({
                    title: "失败",
                    message: "删除失败",
                    type: "error",
                    duration: 2000,
                });
            }
        });
    }
    return {
        handleDelete2
    }
}

export default {
    props: {
        preOrderVisible: Boolean,
        goodsId: Number,
        goodsNum: Number,
    },
    emits: ["onClosePreOrderDialog"],
    setup(props, { emit }) {
        const state = reactive({
            username: JSON.parse(sessionStorage.getItem("token")),
            goodsId: props.goodsId,
            goodsNum: props.goodsNum,
            id: props.goodsId,
            preOrderVisible: props.preOrderVisible,
            tabledata1: [],
            tabledata2: [],
            goodsDetail: [],
            total: "",
            tableData: [
                {
                    name: "",
                    price: '',
                    num: '',
                    total: '',
                }
            ],
            form: {
                region: '',
            },
            address: false,
        });
        const address = ref(false);

        const closeDialog = (visible) => {
            emit('onCloseDialog', visible);
        };
        onMounted(() => {
            loadData(state);
        });
        const closePreOrderDialog = (visible) => {
            emit('onClosePreOrderDialog', visible);
        };
        return {
            ...toRefs(state),
            closeDialog,
            closePreOrderDialog,
            ...handleDelete2(state),
            ...usePAddOrder(state, emit),
        }
    },
    data() {
        const nonull = (rule, value, callback) => {
            if (value === "") {
                return callback(new Error("不能为空"));
            } else {
                callback();
            }
        };
        return {
            addressfrom: {
                name: '',
                phone: '',
                detail: '',
                username: JSON.parse(sessionStorage.getItem("token")),
            },
            rules: {
                name: [{ validator: nonull, trigger: "blur" }],
                phone: [{ validator: nonull, trigger: "blur" }],
                detail: [{ validator: nonull, trigger: "blur" }],

            },
        }
    },
    methods: {
        addaddress(from) {

            this.$refs[from].validate((valid) => {
                if (valid) {

                    var param = this.addressfrom;
                    // var param = param)
                    console.log(this.addressfrom)

                    axios({
                        url: "/userAddressAdd",
                        method: "get",
                        params: {
                            username: param.username,
                            name: param.name,
                            phone: param.phone,
                            detail: param.detail,
                        },
                    }).then((res) => {
                        console.log(res.data);
                        if (res.data.code == 200) {
                            ElNotification({
                                title: "成功",
                                message: "添加成功",
                                type: "success",
                                duration: 2000,
                            });
                            this.reload();
                        } else {
                            ElNotification({
                                title: "失败",
                                message: "添加失败",
                                type: "error",
                                duration: 2000,
                            });
                        }
                    });

                } else {
                    ElNotification({
                        title: "提示",
                        message: "请输入正确的格式",
                        type: "error",
                        duration: 2000,
                    });
                    return false;
                }
                return true;
            });
        }
    }
    // 地址
    // data() {
    //     let typeList = [];
    //     axios({
    //         url: '/getGoodsType',
    //         method: 'get',
    //     }).then(res => {

    //         var u = res.data.data;
    //         var i = 0;
    //         for (i; i < u.length; i++) {
    //             // state.goodsForm.typeName.push(u[i].name)
    //             typeList.push(u[i].name)
    //         }
    //         // });
    //     });
    //     return {
    //         typeList: typeList,
    //     }
    // },
}

</script>